﻿using Oracle.ManagedDataAccess.Client;

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;

using static System.Windows.Forms.VisualStyles.VisualStyleElement;

using Timer = System.Timers.Timer;

namespace PTSJSC
{
    public partial class Form1 : Form
    {
        public TreeNode selectedNode;
        public DataSet sqlconds = new DataSet();
        public DataTable sqlcondt = new DataTable();
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//设置该属性 为false
            tabPage1.Parent = null;//数据上传
            tabPage2.Parent = null;//基本信息设置
            tabPage3.Parent = null;//数据库设置
            tabPage5.Parent = null;//脚本执行SQLite
        }

        private void 数据上传ToolStripMenuItem1_Click(object sender, EventArgs e)
        {

            DataSet dslite = ReadSqllite("sjscrwzb");

            DataTable dt = dslite.Tables[0];

            int int1 = dt.Rows.Count;
            //int int2 = dt.Columns.Count;
            for (int i = 0; i < int1; i++)
            {
                TreeNode rootNode = new TreeNode(dt.Rows[i]["name"].ToString());
                treeView1.Nodes.Add(rootNode);
                DataSet dslite1 = ReadSqllite("sjscrwmxb", $"parent='{dt.Rows[i]["xh"].ToString()}'");
                DataTable dt1 = dslite1.Tables[0];
                int int2 = dt1.Rows.Count;
                for (int j = 0; j < int2; j++)
                {
                    TreeNode childNode = new TreeNode(dt1.Rows[j]["name"].ToString());
                    childNode.Name = dt1.Rows[j]["name"].ToString();
                    rootNode.Nodes.Add(childNode);
                }

            }
            tabPage1.Parent = tabControl1;
        }




        /// <summary>
        /// 读取SQLlite数据库
        /// </summary>
        /// <param name="tablename">要读取的表名</param>
        /// <returns></returns>
        public DataSet ReadSqllite(string tablename, string str1 = "")
        {
            string dbPath = "database/ptsjsc.db";
            var connection = new SQLiteConnection($"Data Source={dbPath};Version=3");
            string sqltext;
            if (str1 != "")
            {
                sqltext = $"SELECT * FROM {tablename} where {str1}";
            }
            else
            {
                sqltext = $"SELECT * FROM {tablename}";
            }

            SQLiteDataAdapter adapter = new SQLiteDataAdapter(string.Format(sqltext), connection);
            connection.Open();
            DataSet ds = new DataSet();
            adapter.Fill(ds, tablename);
            connection.Close();
            return ds;
        }

        public void SaveSqllite(string str1 = "")
        {
            string dbPath = "database/ptsjsc.db";
            var connection = new SQLiteConnection($"Data Source={dbPath};Version=3");
            string sqltext;

            sqltext = str1;
            connection.Open();
            SQLiteCommand cmd = new SQLiteCommand();
            cmd.Connection = connection;
            cmd.CommandText = str1;
            cmd.ExecuteNonQuery();
            connection.Close();
        }

        /// <summary>
        /// 点击相应的菜单，加载tabpage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

            TreeNode parentNode = treeView1.SelectedNode.Parent;
            if (parentNode != null)
            {

                selectedNode = treeView1.SelectedNode;


                bool fff = true; //防止重复加载，如果已经加载，切换到已加载的tabpage
                foreach (TabPage tabPage1 in tabControl2.TabPages)
                {
                    if (tabPage1.Text == selectedNode.Name)
                    {
                        fff = false;
                        tabControl2.SelectedTab = tabPage1;
                        break;
                    }
                }

                // 可以根据需要进行操作，例如获取节点的文本
                string selectedNodeText = selectedNode.Text;


                if (fff)
                {
                    //sqlite基本信息
                    DataSet dslite3 = ReadSqllite("jbxxb");
                    DataTable dt3 = dslite3.Tables[0];

                    TabPage tabPage = new TabPage(selectedNode.Name);
                    tabControl2.TabPages.Add(tabPage);
                    tabControl2.SelectedTab = tabPage;

                    #region 任务名称
                    System.Windows.Forms.Label Label1 = new System.Windows.Forms.Label();
                    Label1.Text = "任务名称：";
                    Label1.Location = new Point(42, 33);
                    Label1.Size = new Size(65, 12);
                    tabPage.Controls.Add(Label1);
                    System.Windows.Forms.Label Label2 = new System.Windows.Forms.Label();
                    Label2.Text = selectedNode.Name;
                    Label2.Location = new Point(113, 33);
                    tabPage.Controls.Add(Label2);
                    #endregion


                    #region 源数据库
                    System.Windows.Forms.Label Label3 = new System.Windows.Forms.Label();
                    Label3.Text = "源数据库：";
                    Label3.Location = new Point(42, 77);
                    Label3.Size = new Size(65, 12);
                    tabPage.Controls.Add(Label3);
                    System.Windows.Forms.ComboBox ComboBox = new System.Windows.Forms.ComboBox();
                    DataSet dslite1 = ReadSqllite("sjscrwmxb", $"name = '{selectedNode.Name}'");
                    DataTable dt1 = dslite1.Tables[0];

                    //下拉框增加数据库连接选项
                    DataSet dslite2 = ReadSqllite("sqlcon");
                    DataTable dt2 = dslite2.Tables[0];
                    for (int i = 0; i < dt2.Rows.Count; i++)
                    {
                        ComboBox.Items.Add(dt2.Rows[i]["name"].ToString());
                    }

                    //如果已经保存数据库连接选项，默认选择相应的选项
                    if (dt1.Rows[0]["sqlcon"].ToString().Length > 0)
                    {
                        ComboBox.Text = dt1.Rows[0]["sqlcon"].ToString();
                    }


                    ComboBox.Location = new Point(113, 77);
                    tabPage.Controls.Add(ComboBox);
                    #endregion


                    #region 源存储
                    System.Windows.Forms.Label Label4 = new System.Windows.Forms.Label();
                    Label4.Text = "源数据库：";
                    Label4.Location = new Point(305, 77);
                    Label4.Size = new Size(65, 12);
                    tabPage.Controls.Add(Label4);
                    System.Windows.Forms.TextBox TextBox = new System.Windows.Forms.TextBox();
                    TextBox.Location = new Point(385, 77);
                    TextBox.Size = new Size(280, 21);
                    tabPage.Controls.Add(TextBox);
                    if (dt1.Rows[0]["proc"].ToString().Length > 0)
                    {
                        TextBox.Text = dt1.Rows[0]["proc"].ToString();
                    }
                    else
                    {
                        TextBox.Text = "未设置存储过程，请先设置并保存！";
                    }
                    TextBox.GotFocus += delegate
                    {
                        if (TextBox.Text == "未设置存储过程，请先设置并保存！")
                        {
                            TextBox.Text = "";

                        }

                    };
                    TextBox.LostFocus += delegate
                    {
                        if (TextBox.Text.Length == 0)
                        {
                            TextBox.Text = "未设置存储过程，请先设置并保存！";
                        }


                    };

                    #endregion


                    #region 时间
                    System.Windows.Forms.Label Label6 = new System.Windows.Forms.Label();
                    Label6.Text = "开始时间：";
                    Label6.Location = new Point(42, 115);
                    Label6.Size = new Size(65, 12);
                    tabPage.Controls.Add(Label6);
                    System.Windows.Forms.DateTimePicker DateTimePicker = new System.Windows.Forms.DateTimePicker();
                    DateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss";
                    DateTimePicker.Format = DateTimePickerFormat.Custom;
                    DateTimePicker.Location = new Point(113, 115);
                    DateTimePicker.Size = new Size(160, 21);
                    tabPage.Controls.Add(DateTimePicker);
                    if (dt1.Rows[0]["scsj"].ToString().Length > 0)
                    {
                        DateTimePicker.Value = Convert.ToDateTime(dt1.Rows[0]["scsj"].ToString());
                    }
                    else
                    {
                        //TextBox.Text = "未设置存储过程，请先设置并保存！";
                    }
                    #endregion

                    #region 间隔时间
                    System.Windows.Forms.Label Label7 = new System.Windows.Forms.Label();
                    Label7.Text = "间隔时间(分钟)：";
                    Label7.Location = new Point(305, 115);
                    Label7.Size = new Size(105, 12);
                    tabPage.Controls.Add(Label7);
                    System.Windows.Forms.TextBox TextBox1 = new System.Windows.Forms.TextBox();
                    TextBox1.Location = new Point(415, 115);
                    TextBox1.Size = new Size(250, 21);
                    tabPage.Controls.Add(TextBox1);
                    TextBox1.Text = dt1.Rows[0]["jgsj"].ToString();
                    #endregion

                    #region 目标表
                    System.Windows.Forms.Label Label8 = new System.Windows.Forms.Label();
                    Label8.Text = "目标表：";
                    Label8.Location = new Point(42, 155);
                    Label8.Size = new Size(65, 12);
                    tabPage.Controls.Add(Label8);
                    System.Windows.Forms.TextBox TextBox2 = new System.Windows.Forms.TextBox();
                    TextBox2.Location = new Point(113, 150);
                    TextBox2.Size = new Size(150, 21);
                    tabPage.Controls.Add(TextBox2);
                    TextBox2.Text = dt1.Rows[0]["totable"].ToString();
                    #endregion

                    #region 主键
                    System.Windows.Forms.Label Label9 = new System.Windows.Forms.Label();
                    Label9.Text = "主键：";
                    Label9.Location = new Point(305, 155);
                    Label9.Size = new Size(65, 12);
                    tabPage.Controls.Add(Label9);
                    System.Windows.Forms.TextBox TextBox3 = new System.Windows.Forms.TextBox();
                    TextBox3.Location = new Point(415, 150);
                    TextBox3.Size = new Size(150, 21);
                    tabPage.Controls.Add(TextBox3);
                    TextBox3.Text = dt1.Rows[0]["toid"].ToString();
                    #endregion


                    #region 保存设置
                    System.Windows.Forms.Button bSave = new System.Windows.Forms.Button();
                    bSave.Text = "保存配置";
                    bSave.Location = new Point(415, 195);
                    tabPage.Controls.Add(bSave);
                    bSave.Click += delegate
                    {
                        try
                        {
                            String sqltext = $"update sjscrwmxb set sqlcon='{ComboBox.Text}',proc='{TextBox.Text}',totable='{TextBox2.Text}',toid='{TextBox3.Text}',scsj='{DateTimePicker.Value}',jgsj='{TextBox1.Text}' where name ='{dt1.Rows[0]["name"].ToString()}'";
                            SaveSqllite(sqltext);
                            dslite1.Clear();
                            dt1.Clear();
                            dslite1 = ReadSqllite("sjscrwmxb", $"name = '{selectedNode.Name}'");
                            dt1 = dslite1.Tables[0];
                            MessageBox.Show("保存成功");
                        }
                        catch (Exception ee)
                        {
                            MessageBox.Show("保存失败！！！失败原因：" + ee.Message.ToString());
                        }
                    };
                    #endregion

                    #region 启动&停止
                    System.Windows.Forms.Button bTrue = new System.Windows.Forms.Button();
                    System.Windows.Forms.Button bFalse = new System.Windows.Forms.Button();
                    bTrue.Text = "启动";
                    bTrue.Location = new Point(190, 560);
                    bFalse.Text = "停止";
                    bFalse.Location = new Point(530, 560);
                    bFalse.Enabled = false;
                    tabPage.Controls.Add(bTrue);
                    tabPage.Controls.Add(bFalse);

                    Timer timer = new Timer(1000);
                    Timer timer2 = new Timer(1000);
                    int sl = 1;
                    int Minimum = 0;
                    int Maximum = sl;
                    int Value = 0;
                    int ii = 0;
                    int cg = 0;
                    int sb = 0;
                    int hjhz = 0;
                    int hjcg = 0;
                    int hjsb = 0;
                    bool tt = true;
                    System.Windows.Forms.ProgressBar ProgressBar = new System.Windows.Forms.ProgressBar();
                    ProgressBar.Minimum = Minimum;
                    ProgressBar.Maximum = Maximum;
                    ProgressBar.Value = Value;
                    ProgressBar.Step = 1;
                    ProgressBar.Location = new Point(44, 376);
                    ProgressBar.Size = new Size(661, 23);
                    ProgressBar.Visible = false;
                    tabPage.Controls.Add(ProgressBar);
                    System.Windows.Forms.Label Label5 = new System.Windows.Forms.Label();
                    Label5.Location = new Point(50, 402);
                    Label5.Visible = false;
                    Label5.MaximumSize = new Size(0, 0); // 宽度不限制，高度不限制
                    Label5.AutoSize = true; // 开启自动调整大小
                    tabPage.Controls.Add(Label5);
                    bTrue.Click += async delegate
                    {
                        timer = new Timer(1000);

                        tt = true;
                        bFalse.Enabled = true;
                        bTrue.Enabled = false;
                        selectedNode.Text = selectedNodeText + "(已启动)";
                        ProgressBar.Visible = true;
                        Label5.Visible = true;
                        //_timer = new Timer(1000);
                        // 设置Elapsed事件处理程序
                        timer.Elapsed += OnTimedEvent;
                        timer.AutoReset = false;
                        // 启用定时器
                        timer.Start();

                        //在指定时间执行
                        async void OnTimedEvent(Object source, ElapsedEventArgs e1)
                        {
                            //Console.WriteLine("定时器触发时间: {0:HH:mm:ss.fff}", e.SignalTime);
                            //获取当前时间
                            DateTime now = DateTime.Now; // 获取当前时间
                            string ss = dt1.Rows[0]["scsj"].ToString();
                            if (now >= DateTime.Parse(ss))
                            {
                                timer2 = new Timer(1000);
                                //MessageBox.Show("2024-11-04 18:40:00");
                                timer.Stop();

                                timer2.Elapsed += OnTimedUpload;
                                // 设置计时器不是自动重置。这样第一次执行后，计时器就会停止。
                                timer2.AutoReset = false;
                                timer2.Start();

                            }
                        }
                        async void OnTimedUpload(Object source, ElapsedEventArgs e2)
                        {

                            Value = 0;
                            sb = 0;
                            cg = 0;
                            ProgressBar.Value = Value;

                            DataSet ds11 = new DataSet();
                            DataTable dt11 = new DataTable();
                            DataTable dt = new DataTable();
                            DataSet ds22 = new DataSet();
                            DataTable dt22 = new DataTable();
                            DataSet ds33 = new DataSet();
                            DataTable dt33 = new DataTable();
                            DataSet dstime = new DataSet();
                            DataTable dttime = new DataTable();
                            string kssj = "";
                            string jssj = "";

                            #region 操作数据库
                            try
                            {

                                ds11 = ReadSqllite("sqlcon", $"name = '{dt1.Rows[0]["sqlcon"].ToString()}'");
                                dt11 = ds11.Tables[0];

                                ds22 = ReadSqllite("sqlcon", $"name = 'PTK'");
                                dt22 = ds22.Tables[0];
                                ds33 = ReadSqllite("sqlcon", $"name = 'LOG'");
                                dt33 = ds33.Tables[0];
                                //ds33 = ReadSqllite("sqlcon", $"name = 'LOG'");
                                dttime = SqlRead(dt11.Rows[0]["type"].ToString(), dt11.Rows[0]["ip"].ToString(), dt11.Rows[0]["uid"].ToString(), dt11.Rows[0]["pwd"].ToString(), $"exec usp_xjptsjsc_date '{dt1.Rows[0]["totable"].ToString()}','1','',''", dt11.Rows[0]["database"].ToString());
                                kssj = dttime.Rows[0]["kssj"].ToString();
                                jssj = dttime.Rows[0]["jssj"].ToString();
                                dt = SqlRead(dt11.Rows[0]["type"].ToString(), dt11.Rows[0]["ip"].ToString(), dt11.Rows[0]["uid"].ToString(), dt11.Rows[0]["pwd"].ToString(), $"exec {dt1.Rows[0]["proc"].ToString()} '{dt3.Rows[0]["id"].ToString()}','{dt3.Rows[0]["name"].ToString()}','{kssj}','{jssj}'", dt11.Rows[0]["database"].ToString());
                            }
                            catch (Exception ee1)
                            {
                                MessageBox.Show("001:" + ee1.Message.ToString());
                            }

                            if (dt.Rows.Count > 0)
                            {
                                sl = dt.Rows.Count;
                                ProgressBar.Maximum = sl;
                                hjhz = hjhz + sl;

                                string sqlstr1 = $"insert into {dt1.Rows[0]["totable"].ToString()}(";
                                string sqlcol = "";
                                string sqlstr2 = $" values(";
                                for (int j = 0; j < dt.Columns.Count; j++)
                                {
                                    string str = dt.Columns[j].ColumnName.ToString();
                                    sqlcol = sqlcol + str + ",";
                                }
                                sqlcol = sqlcol.Substring(0, sqlcol.Length - 1);
                                sqlstr1 = sqlstr1 + sqlcol + ") ";
                                for (int i = 0; i < dt.Rows.Count; i++)
                                //for (int i = 0; i < 1; i++)
                                {
                                    sqlstr2 = $" values(";
                                    for (int j = 0; j < dt.Columns.Count; j++)
                                    {
                                        if (dt.Rows[i][j].ToString().Length > 16)
                                        {
                                            if (dt.Rows[i][j].ToString().Substring(4, 1) == "-" && dt.Rows[i][j].ToString().Substring(7, 1) == "-")
                                            {
                                                if (dt22.Rows[0]["type"].ToString() == "Oracle")
                                                {
                                                    sqlstr2 = sqlstr2 + "to_date('" + dt.Rows[i][j].ToString() + "','yyyy-mm-dd hh24:mi:ss'),";
                                                }
                                                else
                                                {
                                                    sqlstr2 = sqlstr2 + "to_date('" + dt.Rows[i][j].ToString() + "','yyyy-mm-dd hh24:mi:ss'),";
                                                }
                                            }
                                            else sqlstr2 = sqlstr2 + "'" + dt.Rows[i][j].ToString() + "',";
                                        }
                                        else
                                            sqlstr2 = sqlstr2 + "'" + dt.Rows[i][j].ToString() + "',";
                                    }
                                    sqlstr2 = sqlstr2.Substring(0, sqlstr2.Length - 1) + ")";
                                    string sqlstr = sqlstr1 + sqlstr2;
                                    //DataSet ds22 = ReadSqllite("sqlcon", $"name = 'PTK'");
                                    //DataTable dt22 = ds22.Tables[0];
                                    //DataSet ds33 = ReadSqllite("sqlcon", $"name = 'LOG'");
                                    //DataTable dt33 = ds33.Tables[0];

                                    string sqlstr3 = $"select * from {dt1.Rows[0]["totable"].ToString()} where {dt1.Rows[0]["toid"].ToString()}='{dt.Rows[i][$"{dt1.Rows[0]["toid"].ToString()}"].ToString()}'";
                                    DataTable dtt = new DataTable();
                                    try
                                    {
                                        dtt = SqlRead(dt22.Rows[0]["type"].ToString(),
                                      dt22.Rows[0]["ip"].ToString(),
                                       dt22.Rows[0]["uid"].ToString(),
                                      dt22.Rows[0]["pwd"].ToString(),
                                       sqlstr3,
                                       dt22.Rows[0]["database"].ToString());
                                    }
                                    catch (Exception ee2)
                                    {
                                        MessageBox.Show("查询重复：" + ee2.Message.ToString());
                                    }

                                    if (dtt.Rows.Count > 0)
                                    {
                                        string sqlstr4 = $"delete {dt1.Rows[0]["totable"].ToString()} where {dt1.Rows[0]["toid"].ToString()}='{dt.Rows[i][$"{dt1.Rows[0]["toid"].ToString()}"].ToString()}'";
                                        string connectionString = $"User Id={dt22.Rows[0]["uid"].ToString()}; Password={dt22.Rows[0]["pwd"].ToString()};Data Source={dt22.Rows[0]["ip"].ToString()}";
                                        OracleConnection con = new OracleConnection(connectionString);
                                        con.Open();
                                        OracleCommand cmd = new OracleCommand(sqlstr4, con);
                                        int cxhs = cmd.ExecuteNonQuery();
                                        //OracleDataReader reader = cmd.ExecuteReader();
                                        con.Close();
                                    }



                                    string ssss = SqlSave(dt22.Rows[0]["type"].ToString(), dt22.Rows[0]["ip"].ToString(), dt22.Rows[0]["uid"].ToString(), dt22.Rows[0]["pwd"].ToString(), sqlstr);
                                    if (ssss != "true")
                                    {
                                        DateTime now = DateTime.Now;
                                        //保存错误日志
                                        string sf = SqlSave(dt33.Rows[0]["type"].ToString(),
                                            serverip: dt33.Rows[0]["ip"].ToString(),
                                            dt33.Rows[0]["uid"].ToString(),
                                            dt33.Rows[0]["pwd"].ToString(),
                                            $"insert into ptsjsc_log(tablename,rc,cc,zj,zjvalue,datatime) values('{dt1.Rows[0]["totable"].ToString()}','{sqlstr.Replace("'", "''")}','{ssss}','{dt1.Rows[0]["toid"].ToString()}','{dt.Rows[i][$"{dt1.Rows[0]["toid"].ToString()}"].ToString()}','{now.ToString("yyyy-MM-dd HH:mm:ss")}')",
                                            dt33.Rows[0]["database"].ToString());
                                        sb = sb + 1;
                                        hjsb = hjsb + 1;
                                    }
                                    else
                                    {
                                        cg = cg + 1;
                                        hjcg = hjcg + 1;
                                    }

                                    if (tt)
                                    {

                                        //Thread.Sleep(2000);
                                        //await Task.Delay(500); // 延时2秒
                                        ProgressBar.PerformStep();
                                        //ProgressBar.Value = i;
                                        Value = i;
                                        double ff = Math.Round((ProgressBar.Value / (sl * 1.00)) * 100, 2);
                                        Label5.Text = $"总数：{sl}，当前进度：{ProgressBar.Value}，成功：{cg}条，失败：{sb}条，进度百分比：{ff}%,此次启动合计：{hjhz}条，成功：{hjcg}条，失败：{hjsb}条";
                                    }
                                    else
                                    {
                                        break;
                                    }

                                }
                                SqlSave(dt11.Rows[0]["type"].ToString(), dt11.Rows[0]["ip"].ToString(), dt11.Rows[0]["uid"].ToString(), dt11.Rows[0]["pwd"].ToString(), $"exec usp_xjptsjsc_date '{dt1.Rows[0]["totable"].ToString()}','2','{kssj}','{jssj}'", dt11.Rows[0]["database"].ToString());
                            }
                            timer2.Interval = int.Parse(dt1.Rows[0]["jgsj"].ToString()) * 60 * 1000;
                            timer2.Start();
                        }

                        #endregion

                        #region 进度条
                        //for (int i = ii; i <= sl; i++)
                        //{
                        //    if (tt)
                        //    {

                        //        //Thread.Sleep(2000);
                        //        await Task.Delay(500); // 延时2秒
                        //        ProgressBar.PerformStep();
                        //        //ProgressBar.Value = i;
                        //        Value = i;
                        //        double ff = (ProgressBar.Value / (sl * 1.00)) * 100;
                        //        Label5.Text = $"总数：{sl}，当前进度：{ProgressBar.Value}，成功：{cg}条，失败：{sb}条，进度百分比：{ff}%";
                        //    }
                        //    else
                        //    {
                        //        break;
                        //    }

                        //}
                        #endregion
                    };
                    bFalse.Click += delegate
                    {
                        bFalse.Enabled = false;
                        bTrue.Enabled = true;
                        selectedNode.Text = selectedNode.Name;
                        tt = false;
                        ProgressBar.Value = Value;
                        //_timer2.Stop();
                    };
                    #endregion
                    // 输出选中节点的文本
                    //MessageBox.Show("选中的节点是: " + selectedNodeText+",NAME是："+selectedNode.Name);
                }
            }
        }

        /// <summary>
        /// 读取数据库信息
        /// </summary>
        /// <param name="type">数据库类型</param>
        /// <param name="serverip">数据库IP</param>
        /// <param name="uid">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="sqlstr">sql语句</param>
        /// <param name="database">数据库名称，Oracle不需要</param>
        /// <returns></returns>
        public DataTable SqlRead(string type, string serverip, string uid, string password, string sqlstr, string database = "")
        {
            if (type == "SQLServer")
            {
                string strConnection = "uid=" + uid +
                    "; password=" + password +
                    ";Database=" + database +
                    ";Server=" + serverip +
                    ";Connect Timeout=10;TrustServerCertificate=True";
                DataSet dt = new DataSet();
                try
                {
                    using (SqlConnection objConnection = new SqlConnection(strConnection))
                    {
                        int asdad = objConnection.ConnectionTimeout;
                        objConnection.Open();
                        SqlCommand sqlcom = new SqlCommand(sqlstr, objConnection);
                        SqlDataAdapter da = new SqlDataAdapter(sqlcom);
                        da.SelectCommand.CommandTimeout = 600;
                        da.Fill(dt);
                        da.Dispose();
                        DataTable dataTable = dt.Tables[0];
                        objConnection.Close();
                        return dataTable;
                    };
                }
                catch (SqlException sqlex)
                {
                    MessageBox.Show("SQLServer数据库连接错误：" + sqlex.Message.ToString());
                    DataTable dataTable = dt.Tables[0];
                    return dataTable;
                };



            }
            else if (type == "Oracle")
            {
                DataSet ds = new DataSet();
                DataTable Tables = new DataTable();
                Tables.TableName = "Table";
                ds.Tables.Add(Tables);
                string connectionString = "User Id=" + uid + "; Password=" + password + ";Data Source=" + serverip;
                // 创建Oracle连接
                using (OracleConnection con = new OracleConnection(connectionString))
                {
                    using (OracleCommand cmd = new OracleCommand(sqlstr, con))
                    {
                        con.Open();
                        using (OracleDataReader reader = cmd.ExecuteReader())
                        {
                            ds.Load(reader, LoadOption.OverwriteChanges, Tables);
                            con.Close();
                            return Tables;
                        }
                    }
                }
            }
            else
            {
                DataTable Tables = new DataTable();
                return Tables;
            }
        }
        /// <summary>
        /// 保存数据库数据
        /// </summary>
        /// <param name="type"></param>
        /// <param name="serverip"></param>
        /// <param name="uid"></param>
        /// <param name="password"></param>
        /// <param name="sqlstr"></param>
        /// <param name="database"></param>
        /// <returns></returns>
        public String SqlSave(string type, string serverip, string uid, string password, string sqlstr, string database = "")
        {
            if (type == "SQLServer")
            {
                try
                {
                    //sqlstr.Replace("'", "''");
                    //string sqlstr1 = sqlstr.Replace("'", "''");
                    string strConnection = "uid=" + uid + "; password=" + password + ";Database=" + database + ";Server=" + serverip + ";TrustServerCertificate=True";
                    SqlConnection objConnection = new SqlConnection(strConnection);
                    objConnection.Open();
                    SqlCommand sqlcom = new SqlCommand(sqlstr, objConnection);
                    SqlDataAdapter da = new SqlDataAdapter(sqlcom);
                    DataSet dt = new DataSet();
                    da.Fill(dt);
                    //DataTable dataTable = dt.Tables[0];
                    objConnection.Close();
                    return "true";
                }
                catch (Exception e)
                {
                    return e.Message.ToString();
                }

            }
            else if (type == "Oracle")
            {
                DataSet ds = new DataSet();
                DataTable Tables = new DataTable();
                Tables.TableName = "Table";
                ds.Tables.Add(Tables);
                string connectionString = "User Id=" + uid + "; Password=" + password + ";Data Source=" + serverip;
                //string connectionString = "User Id=YAYYX; Password=otSqlaNTh4mBgm4K;Data Source=192.168.1.245:1521/orcl";
                // 创建Oracle连接
                using (OracleConnection con = new OracleConnection(connectionString))
                {
                    try
                    {
                        con.Open();

                        // 创建命令
                        OracleCommand cmd = con.CreateCommand();

                        // 执行查询
                        cmd.CommandText = sqlstr;
                        OracleDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            //Console.WriteLine(reader.GetString(0)); // 假设第一列是字符串类型
                            string asd = reader.GetString(0);
                        }
                        reader.Close();

                        // 执行更新
                        //cmd.CommandText = "UPDATE your_table SET column_name = 'new_value' WHERE condition";
                        //int rowsAffected = cmd.ExecuteNonQuery();
                        //Console.WriteLine("Rows Affected: {0}", rowsAffected);

                        // 关闭连接
                        con.Close();
                        return "true";
                    }
                    catch (OracleException oe)
                    {
                        return oe.Message.ToString();
                    }


                }
            }
            else
            {
                return "入参不对！！！！";
            }
        }

        public void savelog()
        {

        }

        private void 数据库设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabPage3.Parent = tabControl1;
            sqlconds.Clear();
            sqlcondt.Clear();
            sqlconds = ReadSqllite("sqlcon");
            sqlcondt = sqlconds.Tables[0];
            comboBox1.Items.Clear();
            for (int i = 0; i < sqlcondt.Rows.Count; i++)
            {
                comboBox1.Items.Add(sqlcondt.Rows[i]["name"].ToString());
            }

        }

        private void 一键部署ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 脚本执行SQLiteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabPage5.Parent = tabControl1;
        }
        /// <summary>
        /// 数据库设置-保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                String sqltext1 = $"update sqlcon set ip='{textBox2.Text}',uid='{textBox3.Text}',pwd='{textBox4.Text}',database='{textBox5.Text}',type='{comboBox2.Text}' where name ='{textBox1.Text}'";
                SaveSqllite(sqltext1);
                sqlconds = ReadSqllite("sqlcon");
                sqlcondt = sqlconds.Tables[0];
                MessageBox.Show("保存成功！");
            }
            catch (Exception ex2)
            {
                MessageBox.Show(ex2.Message.ToString());
            }

        }

        /// <summary>
        /// 数据库设置-连接测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string ss;
            if (comboBox2.Text == "SQLServer")
            {
                ss = "select 1";
            }
            else
            {
                ss = "select '1' from dual";
            }
            try
            {
                DataTable dtcs = SqlRead(comboBox2.Text, textBox2.Text, textBox3.Text, textBox4.Text, ss, textBox5.Text);
                MessageBox.Show("连接成功");
            }
            catch (Exception ex1)
            {
                MessageBox.Show(ex1.Message.ToString());
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            // 查询DataTable
            DataRow[] selectedRows = sqlcondt.Select($"name = '{comboBox1.Text}'");


            textBox1.Text = selectedRows[0][0].ToString();
            textBox2.Text = selectedRows[0][1].ToString();
            textBox3.Text = selectedRows[0][2].ToString();
            textBox4.Text = selectedRows[0][3].ToString();
            textBox5.Text = selectedRows[0][4].ToString();
            comboBox2.Text = selectedRows[0][5].ToString();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            tabPage3.Parent = null;
            comboBox1.Items.Clear();
            sqlconds.Clear();
            sqlcondt.Clear();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                SaveSqllite(textBox6.Text);
                MessageBox.Show("保存成功！");
            }
            catch (Exception ex2)
            {
                MessageBox.Show(ex2.Message.ToString());
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            tabPage5.Parent = null;
        }

        private void 基本信息设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabPage2.Parent = tabControl1;
            DataSet dslite3 = ReadSqllite("jbxxb");
            DataTable dt3 = dslite3.Tables[0];
            textBox7.Text = dt3.Rows[0]["id"].ToString();
            textBox8.Text = dt3.Rows[0]["name"].ToString();

        }
        /// <summary>
        /// 基本信息保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {

            try
            {
                SaveSqllite($"update jbxxb set id='{textBox7.Text}',name='{textBox8.Text}'");
                MessageBox.Show("保存成功！");
            }
            catch (Exception ex2)
            {
                MessageBox.Show(ex2.Message.ToString());
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            tabPage2.Parent = null;
        }
    }
}
